<script setup lang="ts">
  import { getCodeAPI, loginByCodeAPI } from '@/api/user'
  import { useUserStore } from '@/stores/user'
  import { ref } from 'vue'

  defineOptions({
    options: {
      styleIsolation: 'shared',
    },
  })

  const store = useUserStore()

  const showCountDown = ref(false)
  const changeCountDown = async () => {
    try {
      await formRef.value?.validateField!(['mobile'])
      const res = await getCodeAPI({ mobile: formData.value.mobile, type: 'login' })
      formData.value.code = res.code
      showCountDown.value = true
    } catch (error) {}
  }
  // 表单数据
  const formData = ref({
    mobile: '13230000033',
    code: '',
  })
  const onLogin = async () => {
    await formRef.value?.validate!()
    if (!isAgree.value) {
      uni.showToast({
        title: '请先同意用户协议',
      })
      return
    }
    const res = await loginByCodeAPI(formData.value)
    store.token = res.token
    // 存储用户的Id
    store.userId = res.id
    uni.showToast({
      title: '登录成功',
      icon: 'none',
    })
    uni.switchTab({
      url: '/pages/index/index',
    })
  }
  // 验证表单数据的规则
  const formRules = {
    mobile: {
      rules: [
        { required: true, errorMessage: '请填写手机号码' },
        { pattern: /^1\d{10}$/, errorMessage: '手机号码格式不正确' },
      ],
    },
    code: {
      rules: [
        { required: true, errorMessage: '请输入验证码' },
        { pattern: /^\d{6}$/, errorMessage: '验证码格式不正确' },
      ],
    },
  }
  const formRef = ref<UniHelper.UniFormsInstance>()
  const isAgree = ref(false)
</script>

<template>
  <uni-forms :model="formData" :rules="formRules" class="login-form" ref="formRef">
    <uni-forms-item name="mobile">
      <uni-easyinput
        v-model="formData.mobile"
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <uni-forms-item name="code">
      <uni-easyinput
        v-model="formData.code"
        :input-border="false"
        :clearable="false"
        placeholder="请输入验证码"
        placeholder-style="color: #C3C3C5"
      />
      <text v-if="!showCountDown" @click="changeCountDown" class="text-button">获取验证码</text>

      <view class="text-button" v-else>
        <uni-countdown
          color="#16c2a3"
          :second="59"
          :show-day="false"
          :showHour="false"
          :showMinute="false"
          @timeup="showCountDown = false"
        />后重新获取
      </view>
    </uni-forms-item>

    <view class="agreement">
      <radio :checked="isAgree" @click="isAgree = !isAgree" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="onLogin">登 录</button>
  </uni-forms>
</template>

<style lang="scss">
  @import './styles.scss';
</style>
